//
//  PKHomeViewController.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/8.
//

import UIKit
import Foundation
import SideMenu
import BetterSegmentedControl
import IQTextView
import Koloda
import pop
//import JXPopupView
import SnapKit
import RxSwift
import RxCocoa
import NSObject_Rx
import HXPhotoPicker
import SwiftEntryKit
import RxDataSources
import DynamicColor

private let numberOfCards: Int = 5
private let frameAnimationSpringBounciness: CGFloat = 9
private let frameAnimationSpringSpeed: CGFloat = 16
private let kolodaCountOfVisibleCards = 2
private let kolodaAlphaValueSemiTransparent: CGFloat = 0.1
class PKHomeViewController: PKBaseViewController  ,NavigationBarConfigurable {
    //    let side = PKSideMenuViewController()
    var kolodaView =  CustomKolodaView()
    let leftController = SideMenuNavigationController(rootViewController: PKSideMenuViewController())
    var backView =  BlurImageView()
    var textView = IQTextView()
    let generateButton = PopRippleButton.createRipple(type: .custom, title: "")
    var collectionView : UICollectionView!
    var uploadImageView : UIButton!
    var shouldHideNavigationBar: Bool { false }
    var config: PickerConfiguration = .init()
    var control : BetterSegmentedControl!
    var selectImage : UIImage?
    var text : String?
    var taskID: String?
    var checkButton = UIButton(type: .custom)
    var textImageView : UIButton!
    let isPolling = BehaviorRelay<Bool>(value: true)
    var pollingDisposable : Disposable?
    let polling = PKPollingController<PKTaskResponseModal>()
    var hasFinished: Bool = false
    var resultImage = UIImage()
    let viewModal = PKHomeViewModal()
    var imageSizes: [CGSize] = [CGSize.init(width: 720, height: 1280)]
    let homeImage = ["home1","home2","home3","home4","home5","home6","home7","home8"]
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        updateNavBarVisibility(animated: false)
    }
    
    override func setupUI() {
        view.backgroundColor = .white
        title = "Custom Ghibli Tattoo with AI"
        let button = UIButton(type: .custom)
        button.setImage(.init(named: "menu"), for: .normal)
        button.contentMode = .scaleAspectFit
        button.imageView?.contentMode = .scaleAspectFit
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: button)
        button.rx.tap.subscribe { _ in
            let price = PKSubcriptionViewController()
            self.navigationController?.pushViewController(price, animated: true)
        }.disposed(by: rx.disposeBag)
        
        setupSideMenu()
        let color  = UIColor.black
        control = BetterSegmentedControl(
            frame: .zero,
            segments: LabelSegment.segments(withTitles: [ "Picture to Tatto"],
                                            normalFont: .adaptedBoldFont(size: 15), normalTextColor: .white,selectedFont: .adaptedBoldFont(size: 15),
                                            selectedTextColor: .white),
            options:[.backgroundColor(.systemOrange),
                     .indicatorViewBackgroundColor(UIColor(hexString: "eb4433")),
                     .indicatorViewBorderColor(.white),
                     .indicatorViewBorderWidth(1.0),
                     .cornerRadius(5),
                     .animationSpringDamping(0.8)])
      
        control.addTarget(self,
                          action: #selector(navigationSegmentedControlValueChanged(_:)),
                          for: .valueChanged)
        backView.image = .init(named: "backImage")
        backView.contentMode = .scaleAspectFill
        let image = UIImage(named: "backImage")
        backView.setImage(image!)
        backView.blurRadius = 8
        view.addSubview(backView)
        backView.addSubview(control)
        
        textView.placeholder = "Type here a detailed description of what you want to see in your tattoo..."
        textView.tintColor = color
        backView.addSubview(textView)
        textView.font = .adaptedSystemFont(size: 17)
 
        generateButton.setTitle("Generate", for: .normal)
        generateButton.layer.cornerRadius  = 5
        generateButton.clipsToBounds = true
        generateButton.backgroundColor = .systemOrange
        generateButton.titleLabel?.font = .adaptedBoldFont(size: 16)
        generateButton.titleLabel?.textColor = .white
        generateButton.rippleColor = .systemRed
        view.addSubview(generateButton)
        
        config.selectMode = .single
        config.selectOptions = .photo
        config.photoList.finishSelectionAfterTakingPhoto = true
        config.photoSelectionTapAction = .preview
        config.editor.isFixedCropSizeState = true
        config.editor.cropSize.isRoundCrop = true
        config.editor.cropSize.aspectRatios = []
        config.editor.cropSize.isFixedRatio = true
        config.editor.cropSize.isResetToOriginal = false
        
        uploadImageView = UIButton(type: .custom)
        backView.addSubview(uploadImageView)
        
        uploadImageView.layer.cornerRadius = 5
        uploadImageView.setTitle("Click Here to upload an image", for: .normal)
        uploadImageView.setTitleColor(.gray, for: .normal)
        uploadImageView.imageView?.contentMode = .scaleAspectFit
//        textImageView = UIButton(type: .custom)
        uploadImageView.backgroundColor = .white
        let layout = HorizontalWaterFallLayout()
        layout.delegate = self
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
        collectionView.backgroundColor = .white
        collectionView.showsHorizontalScrollIndicator = false
        view.addSubview(collectionView)
        
        // 示例图片尺寸
        imageSizes = (0..<homeImage.count).map { _ in
//            let w = 540
            let h = CGFloat.random(in: 600...700)
            return CGSize(width: 540, height: h)
        }

        self.view.addSubview(self.collectionView!)
        collectionView.register(UINib.init(nibName: "PKHomeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "PKHomeCollectionViewCell")

        
    }
    
    override func setuplayout() {
        control?.snp.makeConstraints { make in
            make.top.equalTo(10)
            make.centerX.equalToSuperview()
            make.width.equalTo(ScreenAdapter.x(140))
            make.height.equalTo(ScreenAdapter.x(40))
        }
        backView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.top.equalTo(DeviceHelper.navigationFullHeight)
            make.height.equalTo(ScreenAdapter.x(ScreenAdapter.baseHeight*0.35))
        }
        generateButton.snp.makeConstraints { make in
            make.top.equalTo(backView.snp.bottom).offset(10)
            //            make.centerX.equalToSuperview()
            make.left.equalTo(50)
            make.right.equalTo(-50)
            //            make.width.equalTo(ScreenAdapter.x(140))
            make.height.equalTo(ScreenAdapter.x(44))
        }
        uploadImageView.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(control.snp.bottom).offset(10)
            make.bottom.equalTo(backView.snp.bottom).offset(-10)
        }
        collectionView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalTo(generateButton.snp.bottom).offset(10)
            make.height.equalTo(360)
        }


    }
    func testCompose() {
        Task {
            let composer = SplitVideoComposer()
            let videoURL = Bundle.main.url(forResource: "db", withExtension: "mp4")!
            let image = UIImage(named: "backImage")!
            let outputURL = FileManager.default.temporaryDirectory.appendingPathComponent("output.mp4")

            let config = SplitVideoComposer.Config(
                videoURL: videoURL,
                image: image,
                outputURL: outputURL,
                fps: 30,
                outputSize: nil // 自动使用视频尺寸
            )

            do {
                let resultURL = try await composer.compose(with: config)
                print("✅ 合成完成: \(resultURL)")
            
            } catch {
                print("❌ 合成失败: \(error)")
            }
        }
    }
    
    override func bindEvents() {
        
        
        generateButton.rx.tap.subscribe { [self] _ in
            print("continue")
            if control.index == 0 {
                if textView.text.count == 0{
                    var descriptionString: String
                    //                    var descriptionThumb: String
                    descriptionString = "Please write a description for generating sushi pictures"
                    Popup.shared.showNotificationMessage(attributes: Popup.shared.attributes(), title: "Tips", desc: descriptionString, textColor: EKColor(.white))
                    
                } else {
                    guard  TokenManager.shared.token?.count != 0 else {
                        ///跳转登录
                        let login = PKLoginViewController()
                        self.navigationController?.pushViewController(login, animated: true)
                        login.loginSuccess.subscribe {  str  in
                            
                            
                            
                        }.disposed(by: rx.disposeBag)
                        return}
                    self.showLoading(mesage: "Uploading...")
                    NetworkManager.shared.requestAuthObject(.uploadImage(image: nil, description: textView.text, color_type: "2", size: "1:1", img_type: "2"), type: PKTaskModal.self, using: NetworkManager.shared.authprovider).subscribe { [self] modal in
                        guard let task = modal.task_id else {
                            ///错误处理
                            return}
                        self.taskID = task
                        //                            self.isPolling.accept(true)
                        polling.start(pollInterval: .seconds(2)) {
                            NetworkManager.shared.requestAuthObject(.tasks(taskId: self.taskID ?? ""), type: PKTaskResponseModal.self,using: NetworkManager.shared.authprovider)
                        } onNext: { [self] modal in
                            guard  modal.statusCode != "400" else {
                                var descriptionString: String
                                //                    var descriptionThumb: String
                                descriptionString =  modal.message!
                                Popup.shared.showNotificationMessage(attributes: Popup.shared.attributes(), title: "tips", desc: descriptionString, textColor: EKColor(.white))
                                return}
                            guard let progressString = modal.progress,
                                  let progress = Double(progressString) else {
                                
                                
                                
                                return }
                            let percentage = "Generate  " +  "\(Int(progress * 100))%"
                            print(percentage)  // 输出: 14%
                            SetAnotherMessage(message: percentage)
                            
                            guard let urlString = modal.imageUrl?.first as? String else {
                                ///错误提示
                                
                                
                                return }
                            self.polling.stop()
                            NetworkManager.shared.downloadImage(from: urlString).subscribe { [ self] image in
                                //                               let file =  PKFileManager.shared.saveImageToDocuments(image: image)
                                //                                printG(file)
                                self.resultImage = image
                                
                                //如果contentView重载了intrinsicContentSize属性并返回其内容的CGSize，就无需再设置width、height值。
                                //                                let layout: BaseAnimator.Layout = .center(.init(offsetY: 0, offsetX: 0, width: 200, height: 200))
                                //                                //- 确定动画效果
                                //                                let animator = FadeInOutAnimator(layout: layout)
                                //                                //- 初始化JXPopupView
                                //                                let contentView = PKGbiliView()
                                //                                let popupView = JXPopupView(containerView: self.view, contentView: contentView, animator: animator)
                                //                                //- 配置交互
                                //                                popupView.isDismissible = true
                                //                                popupView.isInteractive = true
                                //                                popupView.isPenetrable = false
                                //                                //- 配置背景
                                //                                popupView.backgroundView.style = self.backgroundStyle
                                //                                popupView.backgroundView.blurEffectStyle = self.backgroundEffectStyle
                                //                                popupView.backgroundView.color = self.backgroundColor
                                //                                //- 展示popupView
                                //                                popupView.display(animated: true, completion: nil)
                                //                                //- 消失popupView
                                //                                //通过extension提供的popupView方法，获取JXPopupView进行操作，可以不用全局持有JXPopupView属性
                                //                                contentView.popupView()?.dismiss(animated: true, completion: nil)
                                
                                
                                
                                
                                //                                let description = "This is the generated tattoo image. Click on \("Result image") to view it, or simply click \("Go it")"
                                //                                let data = PresetsDataSource()
                                //                              let attributes =     data[3,1].attributes
                                //                                Popup.shared.showPopupMessage(attributes: attributes, title: "Tips", titleColor: .white, description: description, descriptionColor: .white, buttonTitleColor: .greenGrass, buttonBackgroundColor: .white,image: image)
                                //                                    self.textImageView.image = image1.element.value
                                //                                    textImageView.setImage(image1.element.value, for: .normal)
                                //                                    self.textImageView.ima
                                self.hideLoading()
                            }onError: { error in
                                ///错误处理
                            }onCompleted: {
                                
                            }.disposed(by: rx.disposeBag)
                            //                            }
                        }
                        polling.triggerPolling()
                    }onError: { error in
                        ///错误处理
                    }onCompleted: {
                        
                    }.disposed(by: rx.disposeBag)
                }
            }else if control.index == 1{
                if selectImage == nil {
                    var descriptionString: String
                    //                    var descriptionThumb: String
                    descriptionString = "Please upload the image that you want to modify."
                    Popup.shared.showNotificationMessage(attributes: Popup.shared.attributes(), title: "tips", desc: descriptionString, textColor: EKColor(.white))
                    
                }else if let image =  selectImage {
                    //                    self.textImageView.image = image
                    
                    guard  TokenManager.shared.token?.count != 0 else {
                        ///跳转登录
                        let login = PKLoginViewController()
                        self.navigationController?.pushViewController(login, animated: true)
                        login.loginSuccess.subscribe {  str  in
                            
                            
                            
                        }.disposed(by: rx.disposeBag)
                        return}

                    self.showLoading(mesage: "Uploading...")
                    NetworkManager.shared.requestAuthObject(.uploadImage(image: image, description: "", color_type: "2", size: "1:1", img_type: "1"), type: PKTaskModal.self, using: NetworkManager.shared.authprovider).subscribe { [self] modal in
                        guard let task = modal.task_id else {
                            ///错误处理
                            return}
                        self.taskID = task
                        //                            self.isPolling.accept(true)
                        polling.start(pollInterval: .seconds(2)) {
                            NetworkManager.shared.requestAuthObject(.tasks(taskId: self.taskID ?? ""), type: PKTaskResponseModal.self,using: NetworkManager.shared.authprovider)
                        } onNext: { [self] modal in
                            guard  modal.statusCode != "400" else {
                                var descriptionString: String
                                //                    var descriptionThumb: String
                                descriptionString =  modal.message!
                                Popup.shared.showNotificationMessage(attributes: Popup.shared.attributes(), title: "tips", desc: descriptionString, textColor: EKColor(.white))
                                return}
                            guard let progressString = modal.progress,
                                  let progress = Double(progressString) else {
                                
                                
                                
                                return }
                            let percentage = "Generate  " +  "\(Int(progress * 100))%"
                            print(percentage)  // 输出: 14%
                            SetAnotherMessage(message: percentage)
                            
                            guard let urlString = modal.imageUrl?.first as? String else {
                                ///错误提示
                                
                                
                                return }
                            self.polling.stop()
                            NetworkManager.shared.downloadImage(from: urlString).subscribe { [ self] image in
                                let file =  PKFileManager.shared.saveImageToDocuments(image: image)
                                printG(file)
                                self.resultImage = image
                                let description = "This is the generated tattoo image. Click on \("Result image") to view it, or simply click \("Go it")"
                                let data = PresetsDataSource()
                                let attributes =     data[3,1].attributes
                                Popup.shared.showPopupMessage(attributes: attributes, title: "Tips", titleColor: .white, description: description, descriptionColor: .white, buttonTitleColor: .greenGrass, buttonBackgroundColor: .white,image: image)
                                
                                let filepath =    PKFileManager.shared.saveImageToDisk(image, fileName: PKFileManager.shared.generateTimestampFileName())
                                
                                
                                //                                Popup.shared.observable.subscribe { name in
                                //
                                //
                                //
                                //                                }onError: { error in
                                //
                                //                                }.disposed(by: rx.disposeBag)
                                //                                    self.textImageView.image = image1.element.value
                                //                                    textImageView.setImage(image1.element.value, for: .normal)
                                //                                    self.textImageView.ima
                                self.hideLoading()
                            }onError: { error in
                                ///错误处理
                            }onCompleted: {
                                
                            }.disposed(by: rx.disposeBag)
                            //                            }
                        }
                        polling.triggerPolling()
                    }onError: { error in
                        ///错误处理
                    }onCompleted: {
                        
                    }.disposed(by: rx.disposeBag)
                }
            }
            
        }.disposed(by: rx.disposeBag)
        
        uploadImageView.rx.tap.subscribe { _ in
            let vc = PhotoPickerController.init(config: self.config)
            vc.pickerDelegate = self
            vc.autoDismiss = false
            self.present(vc, animated: true, completion: nil)
            
            
        }.disposed(by: rx.disposeBag)
        
        
    }
    func startPolling() {
        // 防止重复订阅
        //        guard pollingDisposable == nil else { return }
        
        isPolling.flatMapLatest { shouldPoll -> Observable<Int> in
            return shouldPoll ? Observable<Int>.interval(.seconds(5), scheduler:MainScheduler.instance) : Observable<Int>.empty()
        }.flatMapLatest { _ in
            NetworkManager.shared.requestAuthObject(.tasks(taskId: self.taskID ?? ""), type: PKTaskResponseModal.self,using: NetworkManager.shared.authprovider)
                .catch { error in
                    print("请求失败: \(error)")
                    self.isPolling.accept(false)
                    return Observable<PKTaskResponseModal>.empty() // ✅ 正确类型匹配
                }
        }.subscribe { modal in
            print("收到数据")
            
            
        }.disposed(by: rx.disposeBag)
    }
    override func bindViewModel() {
        
        
        
        
        
        //            Observable<Int>.interval(.seconds(5), scheduler: MainScheduler.instance)
        //                .flatMapLatest { _ in
        //                    NetworkManager.shared.requestAuthObject(.tasks(taskId: self.taskID ?? ""), type: PKTaskResponseModal.self)
        //                        .catch { error in
        //                            print("请求失败: \(error)")
        //                            return Observable<PKTaskResponseModal>.empty() // ✅ 正确类型匹配
        //                        }
        //                }
        //                .observe(on: MainScheduler.instance)
        //                .subscribe(onNext: { model in
        //                    // 使用 model
        //                })
        //                .disposed(by: disposeBag)
        
        
        
        
        //        UserDefaults.standard.setValue("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcHBpZCI6ImN5OTFhZTRlYWExMTI0NjU5NyIsImV4cCI6MTc0ODE2ODQwMSwiaWF0IjoxNzQ3MzA0NDAxLCJpc3MiOiJzZWFXZWJTaXRlIiwidHlwZSI6ImFjY2VzcyIsInVpZCI6MSwid2ViX2lkIjozfQ.17twjjGtaH7aZ73R-YZcYqsZQS89eeONRVkK1TduB0o",forKey: "access_token")
        //        UserDefaults.standard.setValue("cy79c9fd367b5420e3", forKey: "appid")
        //        TokenManager.shared.updateAppid("cy79c9fd367b5420e3")
        //        NetworkManager.shared.requestAuthObject(.uploadUser(user_id: "user_2w6xk6WPbTWtSJFxnhDfRDCUTTewr", email: "Jonathanr44@gmail.com", from_login: "github", avatar: "https://example.com/avatar.jpg", nick_name: "测试"), type: PKTokenModal.self, using: NetworkManager.shared.authprovider).subscribe { modal in
        //
        //            TokenManager.shared.updateToken((modal.access_token))
        ////            TokenManager.shared.updateRefreshToken((modal.refresh_token))
        //
        //        }.disposed(by: rx.disposeBag)
    }
    
    
    private func setupSideMenu() {
        leftController.view.backgroundColor = .systemOrange
        SideMenuManager.default.leftMenuNavigationController = leftController
        let settings = makeSettings()
        SideMenuManager.default.leftMenuNavigationController?.settings = settings
    }
    
    private func makeSettings() -> SideMenuSettings {
        let presentationStyle: SideMenuPresentationStyle = .menuSlideIn
        //        presentationStyle.
        presentationStyle.backgroundColor = .white
        presentationStyle.menuStartAlpha = CGFloat(1.0)
        presentationStyle.menuScaleFactor = CGFloat(1.0)
        presentationStyle.onTopShadowOpacity = 0.5
        presentationStyle.presentingEndAlpha = CGFloat(1.0)
        presentationStyle.presentingScaleFactor = CGFloat(1.0)
        
        var settings = SideMenuSettings()
        settings.presentationStyle = presentationStyle
        settings.menuWidth = min(view.frame.size.width, view.frame.size.height) * CGFloat(0.7)
        //        let styles:[UIBlurEffect.Style?] = [nil, .dark, .light, .extraLight]
        settings.blurEffectStyle = nil
        settings.statusBarEndAlpha = 0
        
        return settings
    }
    
    @objc func navigationSegmentedControlValueChanged(_ sender: BetterSegmentedControl) {
        if sender.index == 0 {
            print("Turning lights on.")
            //            animateToPosition(.init(x: CGRectGetMidX(backView.bounds), y: CGRectGetMidY(backView.bounds)), uploadImageView)
            //            animateWithSpringToPosition(.init(x: kWidth * 2, y: CGRectGetMidY(backView.bounds)), uploadImageView)
            //            animateWithSpringToPosition(.init(x: CGRectGetMidX(backView.bounds), y: CGRectGetMidY(backView.bounds)), textView)
//            uploadImageView.isHidden = true
//            textView.isHidden = false
            
            if #available(iOS 13.0, *) {
                view.backgroundColor = .white
            } else {
                view.backgroundColor = .white
            }
        } else {
//            textView.isHidden = true
//            uploadImageView.isHidden = false
            textView.resignFirstResponder()
            //            animateWithSpringToPosition(.init(x: CGRectGetMidX(backView.bounds), y: CGRectGetMidY(backView.bounds)), uploadImageView)
            //            animateWithSpringToPosition(.init(x: -kWidth * 2, y: CGRectGetMidY(backView.bounds)), textView)
            //            textView.isHidden = false
            print("Turning lights off.")
            //            view.backgroundColor = .lightGray
        }
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}
func animateToPosition(_ position: CGPoint, duration: CFTimeInterval = 0.5,_ popView : UIView) {
    // 创建位置动画
    let animation = POPBasicAnimation(propertyNamed: kPOPLayerPosition)
    animation?.toValue = NSValue(cgPoint: position)
    animation?.duration = duration
    animation?.timingFunction = CAMediaTimingFunction(name: .easeIn)
    
    // 设置动画开始和结束回调
    animation?.completionBlock = {  anim, finished in
        if finished {
            print("动画完成")
            // 可以在这里添加动画完成后的逻辑
        }
    }
    
    // 开始动画
    popView.layer.pop_add(animation, forKey: "positionAnimation")
}


// 执行带弹簧效果的移动动画
func animateWithSpringToPosition(_ position: CGPoint,
                                 springBounciness: CGFloat = 8.0,
                                 springSpeed: CGFloat = 12.0,_ popView : UIView) {
    // 创建弹簧动画
    let animation = POPSpringAnimation(propertyNamed: kPOPLayerPosition)
    animation?.toValue = NSValue(cgPoint: position)
    animation?.springBounciness = springBounciness  // 弹性值，越大弹性越大
    animation?.springSpeed = springSpeed            // 速度值，越大速度越快
    
    // 设置动画开始和结束回调
    animation?.completionBlock = { anim, finished in
        if finished {
            print("弹簧动画完成")
        }
    }
    
    // 开始动画
    popView.layer.pop_add(animation, forKey: "springPositionAnimation")
}

extension PKHomeViewController : KolodaViewDelegate {
    func kolodaDidRunOutOfCards(_ koloda: KolodaView) {
        kolodaView.resetCurrentCardIndex()
    }
    
    func koloda(_ koloda: KolodaView, didSelectCardAt index: Int) {
        UIApplication.shared.openURL(URL(string: "https://yalantis.com/")!)
    }
    
    func kolodaShouldApplyAppearAnimation(_ koloda: KolodaView) -> Bool {
        return true
    }
    
    func kolodaShouldMoveBackgroundCard(_ koloda: KolodaView) -> Bool {
        return false
    }
    
    func kolodaShouldTransparentizeNextCard(_ koloda: KolodaView) -> Bool {
        return true
    }
    
    func koloda(kolodaBackgroundCardAnimation koloda: KolodaView) -> POPPropertyAnimation? {
        let animation = POPSpringAnimation(propertyNamed: kPOPViewFrame)
        animation?.springBounciness = frameAnimationSpringBounciness
        animation?.springSpeed = frameAnimationSpringSpeed
        return animation
    }
}

extension PKHomeViewController : KolodaViewDataSource{
    func kolodaSpeedThatCardShouldDrag(_ koloda: KolodaView) -> DragSpeed {
        return .default
    }
    
    func kolodaNumberOfCards(_ koloda: KolodaView) -> Int {
        return numberOfCards
    }
    
    func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
        if index == 5{
            return UIImageView(image: UIImage(named: "cards_\(1)"))
        }else{
            return UIImageView(image: UIImage(named: "cards_\(index + 1)"))
        }
        
    }
    
    func koloda(_ koloda: KolodaView, viewForCardOverlayAt index: Int) -> OverlayView? {
        let overlay = CustomOverlayView()
        overlay.frame = .init(x: 0, y: 0, width: kWidth, height: kHeight)
        return overlay
    }
}

extension PKHomeViewController  : PhotoPickerControllerDelegate {
    func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) {
        pickerController.dismiss(true) {
            result.getImage { [self] image in
                uploadImageView.setImage(image.first, for: .normal)
                selectImage = image.first
                
            }
        }
    }
    func pickerController(didCancel pickerController: PhotoPickerController) {
        pickerController.dismiss(animated: true, completion: nil)
    }
}

extension PKHomeViewController : UICollectionViewDataSource ,UICollectionViewDelegate,HorizontalWaterfallLayoutDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageSizes.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PKHomeCollectionViewCell", for: indexPath) as! PKHomeCollectionViewCell
        cell.imageView.image = UIImage(named: homeImage[indexPath.row])
        return cell
    }
    
    // MARK: - HorizontalWaterfallLayoutDelegate
    
    func collectionView(_ collectionView: UICollectionView, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return imageSizes[indexPath.item]
    }
    
    func numberOfRows(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func heightForRow(at row: Int) -> CGFloat {
        // 可返回不同 row 的高度
        return 160
    }
}




enum CollectionItem {
    case text(String)
    case image(UIImage)
}

struct CollectionSection {
    var header: String
    var items: [CollectionItem]
}

extension CollectionSection: SectionModelType {
    typealias Item = CollectionItem
    
    init(original: CollectionSection, items: [CollectionItem]) {
        self = original
        self.items = items
    }
}


